﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Threading;
using System.Net;
using System.Xml;
using System.Net.Sockets;

namespace WebTBOld
{
    public partial class FM_SocketServer : Form
    {
        private IPAddress serverEnd;

        private TcpListener tcpFlash;

        private Socket SocketServer;

        private Thread SocketCreate;

        private bool connected;

        private bool closing;

        private bool m_TempOneError;

        private bool m_TempTwoError;

        private Button Bt_SendSample;

        private Label lab1;

        private Label Lab_TimeSquare;

        private Label Lab_Backup;

        private Label label2;

        public FM_SocketServer()
        {
            System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();

            this.serverEnd = IPAddress.Parse("127.0.0.1");
            this.InitSocket();
            Thread thread = new Thread(new ThreadStart(this.GetWeatherOne));
            thread.Start();
        }

        //protected override void Dispose(bool disposing)
        //{
        //    if (disposing && this.components != null)
        //    {
        //        this.components.Dispose();
        //    }
        //    base.Dispose(disposing);
        //}

        //private void FM_SocketServer_FormClosing(object sender, FormClosingEventArgs e)
        //{
        //    Process[] processes = Process.GetProcesses();
        //    for (int i = 0; i <= processes.GetUpperBound(0); i++)
        //    {
        //        if (processes[i].ProcessName == "WeatherServer")
        //        {
        //            processes[i].Kill();
        //        }
        //    }
        //}

        private void GetWeatherOne()
        {
            while (true)
            {
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load("http://w1.weather.gov/xml/current_obs/KNYC.xml");
                    XmlNode node = doc.SelectSingleNode("//current_observation/temp_f");
                    label1.Text = node.InnerText;
                }
                catch (Exception exception)
                {
                    this.m_TempOneError = true;
                }

                Thread.Sleep(3600000);
            }
        }

        public void InitSocket()
        {
            this.tcpFlash = new TcpListener(this.serverEnd, 1234);
            this.tcpFlash.Start();
            this.SocketCreate = new Thread(new ThreadStart(this.StartSocket));
            this.SocketCreate.Start();
            this.MessageBoard("Socket Server Initialized");
        }

        private void invokeAsk(string text)
        {
            if (text == "SocketServer Receive: Ping\0")
            {
                text = "Flash App Connection Completed";
            }
            if (!this.listBox2.InvokeRequired)
            {
                this.listBox2.Items.Insert(0, text);
                return;
            }
            else
            {
                FM_SocketServer.ReturnMsg returnMsg = new FM_SocketServer.ReturnMsg(this.MessageBoard);
                object[] objArray = new object[1];
                objArray[0] = string.Concat(text, " (Invoke)");
                base.Invoke(returnMsg, objArray);
                return;
            }
        }

        private void invokeAsk(int index, string temp)
        {
            if (!this.listBox2.InvokeRequired)
            {
                if (index != 1)
                {
                    this.Lab_Backup.Text = temp;
                    return;
                }
                else
                {
                    this.Lab_TimeSquare.Text = temp;
                    return;
                }
            }
            else
            {
                FM_SocketServer.ReturnTemp returnTemp = new FM_SocketServer.ReturnTemp(this.UpdateLabel);
                object[] objArray = new object[2];
                objArray[0] = index;
                objArray[1] = temp;
                base.Invoke(returnTemp, objArray);
                return;
            }
        }

        public void MessageBoard(string text)
        {
            this.listBox2.Items.Insert(0, text);
        }

        public void socketReceive()
        {
            do
            {
                byte[] numArray = new byte[1024];
                int num = this.SocketServer.Receive(numArray);
                string str = "";
                for (int i = 0; i < num; i++)
                {
                    str = string.Concat(str, Convert.ToChar(numArray[i]));
                    numArray[i] = 0;
                    this.closing = false;
                }
                if (!str.Equals(""))
                {
                    this.invokeAsk(string.Concat("SocketServer Receive: ", str));
                }
                else
                {
                    this.closing = true;
                }
            }
            while (!this.closing);
            this.SocketServer.Close();
            this.invokeAsk("SocketServer Closed");
            this.connected = false;
        }

        public void StartSocket()
        {
            while (true)
            {
                this.SocketServer = this.tcpFlash.AcceptSocket();
                this.connected = true;
                this.invokeAsk("Socket Server Connection Established");
                Thread thread = new Thread(new ThreadStart(this.socketReceive));
                thread.Start();
            }
        }

        private void UpdateLabel(int index, string temp)
        {
            if (index != 1)
            {
                this.Lab_Backup.Text = temp;
                return;
            }
            else
            {
                this.Lab_TimeSquare.Text = temp;
                return;
            }
        }

        public void write(string msg)
        {
            msg = string.Concat(msg, "\0");
            ASCIIEncoding aSCIIEncoding = new ASCIIEncoding();
            if (this.connected)
            {
                this.SocketServer.Send(aSCIIEncoding.GetBytes(msg));
            }
            object[] objArray = new object[4];
            objArray[0] = "Connection:";
            objArray[1] = this.connected;
            objArray[2] = ";SocketServer Sent: ";
            objArray[3] = msg;
            this.invokeAsk(string.Concat(objArray));
        }

        public delegate void ReturnMsg(string msg);

        public delegate void ReturnTemp(int index, string temp);

        private void button1_Click(object sender, EventArgs e)
        {
            Thread t2 = new Thread(new ThreadStart(SendLatest));
            t2.Start();
            button1.Enabled = false;
        }

        private void SendLatest()
        {
            while (true)
            {
                string text = "";
                text = label1.Text + ";";
                text += DateTime.Now.ToString("HH:mm");
                this.write(text);
                Thread.Sleep(60000);
            }
        }
    }
}